package com.spring.Service;

import com.spring.Entity.ContractEntity;
import com.spring.Entity.PaylogEntity;
import com.spring.Entity.UserEntity;
import com.spring.Repository.ContractRepository;
import com.spring.Repository.PaylogRepository;
import com.spring.Service.Interface.ContractService;
import com.spring.Service.Interface.PayLogService;
import com.spring.Util.MD5Util;
import com.spring.Util.STATUS;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Arabira on 2016/8/5.
 */
@Service("payLogService")
@Transactional
public class PayLogServceImpl implements PayLogService {
    @Autowired
    private PaylogRepository paylogRepository;
    @Autowired
    private ContractRepository contractRepository;
    private Map<String, Object> response;

    @Override
    public Map<String, Object> findByContractId(String contractId) {
        response = new HashMap<>();
        if (StringUtils.isBlank(contractId)) {
            response.put("status", "error");
            response.put("description", "合同号为空");
            return response;
        }
        PaylogEntity[] paylogEntities = paylogRepository.findByContractId(contractId);
        response.put("status", "ok");
        response.put("body", paylogEntities);
        return response;
    }

    @Override
    public Map<String, Object> onOrOff(Integer paylogId) {
        response = new HashMap<>();
        PaylogEntity paylogEntity = paylogRepository.findOne(paylogId);
        if (null == paylogEntity) {
            response.put("status", "error");
            response.put("description", "交易记录不存在");
            return response;
        }
        if (paylogEntity.getWarnOrNot()) {
            paylogEntity.setWarnOrNot(false);
        } else {
            paylogEntity.setWarnOrNot(true);
        }
        paylogRepository.saveAndFlush(paylogEntity);
        response.put("status", "ok");
        response.put("description", "修改成功");
        response.put("body", paylogEntity.getWarnOrNot());
        return response;
    }

    //手动添加支付记录
    @Override
    public int addPaylog(PaylogEntity paylogEntity) {
        int status = STATUS.FAIL;
        ContractEntity contractEntity = contractRepository.findOne(paylogEntity.getContractId());
//        contractEntity.setTimes(contractEntity.getTimes() + 1);
        if (null == paylogEntity.getMoney()) {
            if (Integer.valueOf(paylogEntity.getMoney()) < 0) {
                status = STATUS.MONEYERROR;
            } else {
                paylogEntity.setMoney("0");
            }
        }
        if (null == paylogEntity.getWarnOrNot()) {
            paylogEntity.setWarnOrNot(false);
        }
        contractRepository.saveAndFlush(contractEntity);
        paylogRepository.saveAndFlush(paylogEntity);
        return status;
    }

    @Override
    public int update(Integer paylogId, Date paidTime, Date remindTime, String money) {
        response = new HashMap<>();
        int status = STATUS.FAIL;
        PaylogEntity paylogEntity = paylogRepository.findOne(paylogId);
        if (null != paylogEntity) {
            if (null != paidTime && paylogEntity.getPaidTime() != null) {
                if (paylogEntity.getPaidTime().compareTo(paidTime) <= 0 && paylogEntity.getRemindTime().compareTo(paidTime) <= 0) {
                    paylogEntity.setPaidTime(paidTime);
                    status = STATUS.SUCCESS;
                } else {
                    status = STATUS.PAIDTIMEERROR;
                }
            } else {
                paylogEntity.setPaidTime(paidTime);
                status = STATUS.SUCCESS;
            }
            if (null != remindTime) {
                if (paylogEntity.getRemindTime() != null) {
                    if (paylogEntity.getRemindTime().compareTo(remindTime) <= 0 && paylogEntity.getPaidTime().compareTo(remindTime) >= 0) {
                        paylogEntity.setRemindTime(remindTime);
                        status = STATUS.SUCCESS;
                    } else {
                        status = STATUS.REMINDTIMEERROR;
                    }
                } else {
                    paylogEntity.setRemindTime(remindTime);
                    status = STATUS.SUCCESS;
                }
            }
            if (!StringUtils.isBlank(money)) {
                if (Integer.valueOf(money) >= 0) {
                    paylogEntity.setMoney(money);
                    status = STATUS.SUCCESS;
                } else {
                    status = STATUS.MONEYERROR;
                }
            }
            if (status == STATUS.SUCCESS) {
                paylogRepository.saveAndFlush(paylogEntity);
            }
        }
        return status;
    }

    //自动发送邮件使用，根据当前时间查找需要提醒的支付记录
    @Override
    public PaylogEntity[] findPaylogByRemindDate() {
        PaylogEntity[] paylogEntities = paylogRepository.findByRemindTimeAndWarnOrNot(LocalDate.now());
        return paylogEntities;

    }

    @Override
    public String addByExcel(MultipartFile file) throws IOException, BiffException, ParseException {
        String message;
        File file1 = new File("ContractMSTemp");
        FileOutputStream fileOutputStream = new FileOutputStream(file1);
        BufferedOutputStream outputStream = new BufferedOutputStream(fileOutputStream);
        outputStream.write(file.getBytes());
        Workbook workbook = Workbook.getWorkbook(file1);
        Sheet sheet = workbook.getSheet(1);
        int row = sheet.getRows();
        for (int i = 1; i < row; i++) {
            Cell cell = null;
            //合同编号
            PaylogEntity paylogEntity = new PaylogEntity();
            if (null != (cell = sheet.getCell(0, i)) && !StringUtils.isBlank(cell.getContents())) {
                ContractEntity contractEntity = contractRepository.findByContractID(cell.getContents());
                paylogEntity.setContractId(contractEntity.getId());
            } else {
                message = "Sheet2第" + (i+1) + "行：合同编号不为空";
                return message;
            }
            //付款时间
            if (null != (cell = sheet.getCell(1, i)) && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                java.util.Date tempDate = format.parse(str);
                java.sql.Date date = new java.sql.Date(tempDate.getTime());
                paylogEntity.setPaidTime(date);
            } else {
                message = "Sheet2第" + (i+1) + "行：付款时间不能为空";
                return message;
            }
            //付款金额
            if (null != (cell = sheet.getCell(2, i)) && !StringUtils.isBlank(cell.getContents())) {
                paylogEntity.setMoney(cell.getContents());
            } else {
                message = "Sheet2第" + (i+1) + "行：付款金额不能为空";
                return message;
            }
            //是否提醒
            if (null != (cell = sheet.getCell(3, i)) && !StringUtils.isBlank(cell.getContents())) {
                String flag = cell.getContents();
                if (flag == "是") {
                    paylogEntity.setWarnOrNot(true);
                    cell = sheet.getCell(4, i);
                    String str = cell.getContents();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                    java.util.Date tempDate = null;
                    try {
                        tempDate = format.parse(str);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    java.sql.Date date = new java.sql.Date(tempDate.getTime());
                    paylogEntity.setRemindTime(date);
                } else {
                    paylogEntity.setWarnOrNot(false);
                }

            } else {
                message = "Sheet2第" + (i+1) + "行：提醒不能为空";
                return message;
            }
            paylogRepository.saveAndFlush(paylogEntity);
        }
        return null;
    }
}
